/*
 * Copyright (C) 2025 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package top.xbaistack.common;

import lombok.Getter;
import lombok.Setter;
import top.xbaistack.utils.Utils;

/**
 * 统一响应消息格式
 *
 * <pre style="background: #FDFDFD; margin: 0">
 *
 * {
 *     "code": 200,     // 状态码
 *     "message": "OK", // 状态码对应的描述信息
 *     "data": [Object] // 响应核心数据，所有数据都将封装于此属性中
 * }
 * </pre>
 *
 * @author tangxbai
 * @since 2023/03/25
 */
@Getter
@Setter
public class Result<T> {

    private int code;
    private String message = "OK";
    private T data;

    public static final <E> Result<E> fail(String message) {
        Result<E> result = of(Code.FAIL);
        return result.message(message);
    }

    public static final <E> Result<E> of(int code) {
        return new Result<E>().code(code);
    }

    public static final <E> Result<E> of(Code code) {
        return of(code, null);
    }

    public static final <E> Result<E> of(Code code, E data) {
        if (code == null) {
            return ok();
        }
        return new Result<E>().code(code.code()).message(code.message()).data(data);
    }

    public static final <E> Result<E> of(int code, String message) {
        return new Result<E>().code(code).message(message);
    }

    public static final <E> Result<E> ok(E data) {
        final Result<E> result = ok();
        return result.data(data);
    }

    public static final <E> Result<E> ok(String message) {
        final Result<E> result = ok();
        return result.message(message);
    }

    public static final <E> Result<E> ok() {
        return of(Code.OK);
    }

    public Result<T> code(int code) {
        this.code = code;
        return this;
    }

    public Result<T> format(Object... args) {
        this.message = Utils.format(message, args);
        return this;
    }

    public Result<T> message(String message) {
        this.message = message;
        return this;
    }

    public Result<T> data(T data) {
        this.data = data;
        return this;
    }

    public boolean is(Code code) {
        return this.code == code.code();
    }

}
